﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TimKen.BussLogic;
using System.Data;
using TimKen.DataEntity;
using TimKen.Web.UserControls;
using System.Text;

namespace TimKen.Web
{
    public partial class PromotionProducts : TimKen.App.WebPage
    {
        public ProductManager productManager = new ProductManager();
        FavoriteManager frm = new FavoriteManager();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                BindData();
                BindResources();
            }
        }

        private void BindData()
        {
            DataSet ds = productManager.GetPromoteList(AspNetPager1.PageSize, AspNetPager1.CurrentPageIndex, LanguageID, 0, -1, "", "1", true);
            AspNetPager1.RecordCount = Convert.ToInt32(ds.Tables[1].Rows[0]["total"]);

            if (AspNetPager1.RecordCount == 0)
                this.ltEmptyData.Visible = true;
            this.repProduct.DataSource = ds.Tables[0].DefaultView;
            this.repProduct.DataBind();
        }

        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            BindData();
        }

        protected void repProduct_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "AddToShoppingCart")
            {
                UserS u = Session["User"] as UserS;
                //如果用户未登陆，则跳转到注册页面
                if (u == null)
                    Response.Redirect("/User/Register.aspx");
                if (u.UserType == UserType.SelfRegistered)
                {
                    Response.Redirect("/ErrorAuthority.aspx");
                }
                else
                {
                    ImageButton lb = (ImageButton)e.CommandSource;
                    TextBox t = lb.Parent.Controls[4] as TextBox;
                    decimal number = 50;
                    if (!decimal.TryParse(t.Text, out number) || number <= 0)
                    {
                        Alert(GetLangString("InValidNumber"));
                        return;
                    }
                    //ShoppingCartManager scm = new ShoppingCartManager();
                    //ShoppingCart model = new ShoppingCart();
                    int productID = int.Parse(e.CommandArgument.ToString());
                    if (GetProductBasePrice(productID).Price == 0)
                    {
                        Alert(GetLangString("Price0Product"));
                        return;
                    }
                    //model.UserName = CurrentUserName;
                    //model.Number = number;
                    //model.ProductID = productID;
                    //scm.Add(model);
                    //BindData();

                    //Top top = this.Page.Master.FindControl("Top1") as Top;
                    //top.totalCartCount = top.totalCartCount + number;
                    /*
                     * 田勇的新购物车添加方法
                     * */
                    TimKen.DataEntity.Product pr = productManager.GetModel(productID);

                    // TimKen.DataEntity.Product pr = (TimKen.DataEntity.Product)(from r in dsproduct.Tables[0].AsEnumerable() where r["ProductID"].ToString() == productID.ToString() select r);

                    Project pro = new Project();
                    DataSet dsproduct = productManager.GetList(AspNetPager1.PageSize, AspNetPager1.CurrentPageIndex, LanguageID, 0, 0, "", " and a.ProductID=" + productID, false, true, 0);// ("ProductID=" + productID);//
                    foreach (DataRow itemd in dsproduct.Tables[0].Rows)
                    {
                        pro.ProjectXh = itemd["Name"].ToString();
                    }
                    pro.Date = DateTime.Now;// Convert.ToDateTime("2099-12-30");// pr.DateAdded;// DateTime.Now;
                      pro.Min = pr.MinMultiple;
                    pro.MinQuantitative = pr.MinNumber;
                    pro.Netweight = (float)pr.Weight;
                    pro.ProjectId = pr.ItemCode.Trim();// productID.ToString();
                    //pro.ProjectXh = pr.SalesUnit;// pr.CategoryID;
                    pro.Unitprice = GetProductBasePrice(productID).Price; //  GetProductBasePrice(productID).Price.Equals(0)
                    pro.TaxRate = (float)pr.TaxRate;
                    UserAccountManager uam = new UserAccountManager();
                    ProductManager pm = new ProductManager();
                    bool isAuthorizationed = pm.GetProductAuthorization(Convert.ToInt32(pro.ProjectId), uam.GetModel(CurrentUserName).CustomerID.Value);
                    ShopCartItem item = new ShopCartItem(pro, Convert.ToInt32(number), isAuthorizationed);
                    ShopCart.Add(item);

                    Alert(GetLangString("AddProductSuccessful"), "/Product.aspx");
                }
            }
            if (e.CommandName == "Favorite")
            {



                //如果用户未登陆，则跳转到注册页面
                if (CurrentUserName == null)
                    Response.Redirect("/User/Register.aspx");


                TimKen.DataEntity.Favorite favorite = new TimKen.DataEntity.Favorite();
                favorite.DateAdded = DateTime.Now;
                favorite.ProductID = int.Parse(e.CommandArgument.ToString());
                favorite.UserName = CurrentUserName;
                frm.Add(favorite);
                Alert(GetLangString("AddSuccessful"));
            }
        }


        public string GetParentLink(int categoryID)
        {
            PCategoryManager pcm = new PCategoryManager();
            string linkData = pcm.GetAllParent(categoryID, LanguageID);
            string[] links = linkData.Split(',');
            StringBuilder sb = new StringBuilder();
            if (links.Length > 0)
            {
                foreach (string link in links)
                {
                    string[] nameid = link.Split(':');
                    if (nameid.Length == 2)
                    {
                        sb.Append("<a href=\"Category.aspx?cid=" + nameid[1] + "\">" + nameid[0] + "</a>: ");
                    }
                    else
                    {
                        sb.Append(nameid[0]);
                    }
                }
            }
            if (sb.Length > 0)
            {
                sb.Remove(sb.Length - 2, 2);
            }
            return sb.ToString();
        }

        public string GetCategoryImage(int categoryID)
        {
            PCategoryManager pcm = new PCategoryManager();
            return pcm.GetCategoryImage(categoryID);
        }

        public string SetInventoryString(object inventory)
        {
            if ((inventory == null) || (decimal.Parse(inventory.ToString()) <= 0))
            {
                return GetLangString("UnavailableIvq");
            }
            else
            {
                return GetLangString("AvailableIvq");
            }
        }

        protected void BindResources()
        {
            this.ltEmptyData.Text = GetLangString("EmptyData");
        }
    }
}
